package she_ji_mo_shi.dan_li;

/***
 *@title 单例模式
 *@description <TODO 单例模式>
 *@author 许文迪
 *@version 1.0.0
 *@create 2025/6/24 8:52
 **/
public class DanLiDemo {
    public static void main(String[] args) {
        SingletonLazyThreadSafe instance = SingletonLazyThreadSafe.getInstance();
        System.out.println( instance);
    }
}

/**
 * 饿汉式单例模式
 */
class SingletonHungry {
    private static final SingletonHungry s = new SingletonHungry();

    private SingletonHungry() {}

    public static SingletonHungry getInstance() {
        return s;
    }
}

/**
 * 懒汉式单例模式（线程不安全）
 */
class SingletonLazy {
    private static SingletonLazy s;
    private SingletonLazy() {}
    public static SingletonLazy getInstance() {
        if (s == null) {
            s = new SingletonLazy();
        }
        return s;
    }
}

/**
 * 懒汉式单例模式（线程安全）
 */
class SingletonLazyThreadSafe {
    private static SingletonLazyThreadSafe s;
    private SingletonLazyThreadSafe() {}
    public static synchronized SingletonLazyThreadSafe getInstance(){
        if (s == null){
            s = new SingletonLazyThreadSafe();
        }
        return s;
    }
}

/**
 * 双重检查/双重校验 单例模式
 */
class SingletonDoubleCheck {
    private static SingletonDoubleCheck s;
    private SingletonDoubleCheck() {}

    public static SingletonDoubleCheck getInstance(){
        if (s == null){
            synchronized (SingletonDoubleCheck.class){
                if (s == null){
                    s = new SingletonDoubleCheck();
                }
            }
        }
        return s;
    }

}